import Vue from 'vue'

import Vuex, { mapMutations } from 'vuex'

Vue.use(Vuex)
const cart = JSON.parse(localStorage.getItem('cart') || '[]')
const store = new Vuex.Store({
  state: {
    cart: cart
  },
  mutations: {

    addToCart(state, goods) {
      const index = state.cart.findIndex((el) => {
        return el.id === goods.id
      })

      if (index !== -1) {
        state.cart[index].count += goods.count
      } else {
        state.cart.push(goods)
      }

      localStorage.setItem('cart', JSON.stringify(state.cart))

    },
    updateCartCount(state, goods) {
      const index = state.cart.findIndex(el => el.id == goods.id)
      state.cart[index].count = goods.count
      localStorage.setItem('cart', JSON.stringify(state.cart))
    },
    deleteFormCart(state, id) {
      state.cart = state.cart.filter(el => el.id != id)
      console.log(state.cart)
      localStorage.setItem('cart', JSON.stringify(state.cart))

    },
    selectedChange(state, select) {
      state.cart.find(el => el.id == select.id).selected = select.selected
      localStorage.setItem('cart', JSON.stringify(state.cart))
    }
  },
  getters: {
    totalNumber(state) {
      let c = 0
      state.cart.forEach(el => c += el.count)
      return c
    },
    // 获取缓存中的商品数据id, 发送服务器获取数据
    goods_id(state) {
      return state.cart.map(el => el.id).join(',')
    },
    // 选择键值对
    selectObj(state) {
      const o = {}
      state.cart.forEach(el => o[el.id] = el.selected)
      return o
    },
    // 获取 id和数量的键值对
    idAndCount(state) {
      let o = {};
      state.cart.forEach(el => o[el.id] = el.count)
      return o
    },
    totalCount(state) {
      let count = 0
      state.cart.forEach(el => {
        if (el.selected) {
          count += el.count
        }
      })
      return count
    },
    totalPrice(state) {
      let total = 0
      state.cart.forEach(el => {
        if (el.selected) {
          total += +el.sell_price * el.count
        }
      })
      return total
    }
  },
  actions: {}
})

export default store